Telegram Group & Telegram Channel
✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_ci/1346
Create:
Last Update:

✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1346

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

The lead from Wall Street offers little clarity as the major averages opened lower on Friday and then bounced back and forth across the unchanged line, finally finishing mixed and little changed.The Dow added 33.18 points or 0.10 percent to finish at 34,798.00, while the NASDAQ eased 4.54 points or 0.03 percent to close at 15,047.70 and the S&P 500 rose 6.50 points or 0.15 percent to end at 4,455.48. For the week, the Dow rose 0.6 percent, the NASDAQ added 0.1 percent and the S&P gained 0.5 percent.The lackluster performance on Wall Street came on uncertainty about the outlook for the markets following recent volatility.

China’s stock markets are some of the largest in the world, with total market capitalization reaching RMB 79 trillion (US$12.2 trillion) in 2020. China’s stock markets are seen as a crucial tool for driving economic growth, in particular for financing the country’s rapidly growing high-tech sectors.Although traditionally closed off to overseas investors, China’s financial markets have gradually been loosening restrictions over the past couple of decades. At the same time, reforms have sought to make it easier for Chinese companies to list on onshore stock exchanges, and new programs have been launched in attempts to lure some of China’s most coveted overseas-listed companies back to the country.

C C Sharp programming from us


Telegram C# (C Sharp) programming
FROM USA